package com.kakarote.core.exception;

import com.kakarote.core.common.Const;
import com.kakarote.core.common.ResultCode;
import com.kakarote.core.common.enums.SystemCodeEnum;
import lombok.Getter;

/**
 * crm默认的异常处理
 *
 * @author Administrator
 */
@Getter
public class CrmException extends RuntimeException implements ResultCode {

    private final String msg;

    private final int code;

    private Object data;

    public CrmException() {
        super("参数验证错误", null, false, false);
        this.code = SystemCodeEnum.SYSTEM_NO_VALID.getCode();
        this.msg = SystemCodeEnum.SYSTEM_NO_VALID.getMsg();
    }

    public CrmException(int code, String msg) {
        super(code + ":" + msg, null, true, true);
        this.code = code;
        this.msg = msg;
    }

    public CrmException(ResultCode resultCode) {
        this(resultCode.getCode(), resultCode.getMsg());
    }

    public CrmException(ResultCode resultCode, Object... args) {
        this(resultCode.getCode(), String.format(resultCode.getMsg(), args));
    }

    public CrmException(ResultCode resultCode, String str, Boolean flag) {
        this(resultCode.getCode(), resultCode.getMsg() + ":" + str);
    }

    public void setData(Object data) {
        this.data = data;
    }

    /**
     * 检查是否是crm异常
     *
     * @param ex   异常
     * @param dept 深度
     * @return CrmException
     */
    public static CrmException checkCrmException(Exception ex, Integer dept) {
        --dept;
        if (dept < 0) {
            return null;
        }
        if (ex.getCause() == null || !(ex.getCause() instanceof Exception)) {
            return null;
        }
        if (ex.getCause() instanceof CrmException) {
            return (CrmException) ex.getCause();
        }
        return checkCrmException((Exception) ex.getCause(), dept);
    }

    /**
     * 检查是否是crm异常
     *
     * @param ex 异常
     * @return CrmException
     */
    public static CrmException checkCrmException(Exception ex) {
        return checkCrmException(ex, Const.AUTH_DATA_RECURSION_NUM);
    }
}
